﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Antlr.StringTemplate;

namespace MvcDemo.CustomViewEngines
{
    public class StringTemplateViewEngine : VirtualPathProviderViewEngine
    {
        private string _AppPath = string.Empty;

        #region 属性 Properties
        public static FileSystemTemplateLoader Loader { get; private set; }
        public static StringTemplateGroup Group { get; private set; }
        #endregion

        public StringTemplateViewEngine(string appPath)
        {
            _AppPath = appPath;
            Loader = new FileSystemTemplateLoader(appPath);
            Group = new StringTemplateGroup("views", Loader);
            MasterLocationFormats = new[] {
                "/Views/{1}/{0}.st",
                "/Views//Shared/{0}.st" 
            };
            ViewLocationFormats = MasterLocationFormats;
            PartialViewLocationFormats = MasterLocationFormats;
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            return this.CreateView(controllerContext, partialPath, String.Empty);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            StringTemplate stringTemplate = Group.GetInstanceOf(viewPath.Replace(".st", ""));
            StringTemplateView result = new StringTemplateView(stringTemplate);
            return result;
        }
    }
}